package com.lucifer.cloud.auth.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lucifer.cloud.auth.model.Result;
import com.lucifer.cloud.auth.model.response.CaptchaResult;
import com.lucifer.cloud.auth.support.RedisOperator;
import com.lucifer.cloud.auth.support.SmsOperator;
import com.lucifer.cloud.auth.support.SmsResponse;
import com.lucifer.cloud.auth.util.RandomUtil;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static com.lucifer.cloud.auth.constant.RedisConstants.*;

/**
 * 登录接口，登录使用的接口
 *
 * @author lucifer
 */
@RestController
@CrossOrigin
@RequiredArgsConstructor
public class LoginController {

    private final RedisOperator<String> redisOperator;

    @Resource(name = "aliSendSmsOperator")
    private SmsOperator sendSms;

    @GetMapping("/getSmsCaptcha")
    public Result<String> getSmsCaptcha(@RequestParam(name = "phone") String phone, @RequestParam(name = "type")String type) {
        String smsCaptcha  = RandomUtil.get4();
        //String message = tencentSendSmsOperator.sendSms(phone, smsCaptcha);
        SmsResponse smsResponse = sendSms.sendSms(phone, smsCaptcha);
        if("OK".equals(smsResponse.getCode())){
            // 存入缓存中，5分钟后过期
            if("login".equals(type)){
                redisOperator.set((SMS_CAPTCHA_LOGIN_PREFIX_KEY + phone), smsCaptcha, DEFAULT_TIMEOUT_SECONDS);
            }else if("register".equals(type)) {
                redisOperator.set((SMS_CAPTCHA_REGISTER_PREFIX_KEY + phone), smsCaptcha, DEFAULT_TIMEOUT_SECONDS);
            }else if("forget".equals(type)) {
                redisOperator.set((SMS_CAPTCHA_FORGET_PREFIX_KEY + phone), smsCaptcha, DEFAULT_TIMEOUT_SECONDS);
            }else {
                return Result.success("不支持获取短信类型.", null);
            }
            return Result.success("获取短信验证码成功.", smsCaptcha);
        }else {
            return Result.error(smsResponse.getMessage());
        }
    }

    @GetMapping("/getCaptcha")
    public Result<CaptchaResult> getCaptcha() {
        // 使用huTool-captcha生成图形验证码
        // 定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(130, 34, 4, 2);
        // 生成一个唯一id
        long id = IdWorker.getId();
        // 存入缓存中，5分钟后过期
        redisOperator.set((IMAGE_CAPTCHA_PREFIX_KEY + id), captcha.getCode(), DEFAULT_TIMEOUT_SECONDS);
        return Result.success("获取验证码成功.", new CaptchaResult(String.valueOf(id), captcha.getCode(), captcha.getImageBase64Data()));
    }

}
